﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace uz.control
{
    public static class WordIndexManager
    {
        private static WordIndex _EntityWordIndex = null;

        public static WordIndex EntityWordIndex
        {
            get 
            {
                if (_EntityWordIndex == null)
                {
                    _EntityWordIndex = Deserialize("Entity.dat");
                }
                return _EntityWordIndex; 
            }
        }

        private static WordIndex _EntityFieldWordIndex = null;

        public static WordIndex EntityFieldWordIndex
        {
            get
            {
                if (_EntityFieldWordIndex == null)
                {
                    _EntityFieldWordIndex = Deserialize("EntityField.dat");
                }
                return _EntityFieldWordIndex;
            }
        }


        private static WordIndex Deserialize(string fleName)
        {
            WordIndex rst = new WordIndex();

            
            string str = SavePath + fleName;
            if (File.Exists(str) == true)
            {
                try
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    Stream stream = new FileStream(str, FileMode.Open);
                    rst = (WordIndex)bf.Deserialize(stream);
                    stream.Close();
                }
                catch { }
            }

            return rst;
        }

        public static string SavePath
        {
            get
            {
                string str = System.Windows.Forms.Application.StartupPath;
                str += @"\AutoComplateData\";
                if (Directory.Exists(str) == false)
                {
                    Directory.CreateDirectory(str);
                }

                return str;
            }
        }

        private static void Serialize(string fldName, WordIndex wi)
        {
            if (wi == null)
            {
                return;
            }
            string str = SavePath + fldName;
            if (File.Exists(str) == false)
            {
                File.Create(str);
            }

            BinaryFormatter bf = new BinaryFormatter();
            Stream stream = new FileStream(str, FileMode.Open);
            bf.Serialize(stream, wi);
            stream.Close();

        }
        

        public static void Save()
        {
            Serialize("Entity.dat", _EntityWordIndex);
            Serialize("EntityField.dat",_EntityFieldWordIndex);
        }

    }
}
